// components/product-edit/index.js
import componentBehavior from '../../../behaviors/component';
import { COMPONENT_OPTIONS } from '../../../constants/common';
import { swapArr } from '../../../common/utils';

Component({
    behaviors: [componentBehavior],
    options: {
        ...COMPONENT_OPTIONS,
    },
    properties: {
        signinInfo: {
            type: Object,
            value: {},
        },
    },
    data: {
        quantityModal: {
            show: false,
            productId: '',
            quantity: '',
        },
    },
    methods: {
        _handleChange() {
            this.triggerEvent('change', this.data.signinInfo);
        },
        handleUp(e) {
            const { index } = e.currentTarget.dataset;
            let { activityProductWithSkus } = this.data.signinInfo;
            if (index === 0) return;
            activityProductWithSkus = swapArr(activityProductWithSkus, index, index - 1);
            this._handleChange();
        },
        handleDown(e) {
            const { index } = e.currentTarget.dataset;
            let { activityProductWithSkus } = this.data.signinInfo;
            if (index === activityProductWithSkus.length - 1) return;
            activityProductWithSkus = swapArr(activityProductWithSkus, index, index + 1);
            this._handleChange();
        },
        handleRemove(e) {
            const { index } = e.currentTarget.dataset;
            let { activityProductWithSkus } = this.data.signinInfo;
            activityProductWithSkus.splice(index, 1);
            this._handleChange();
        },
        handleShowQuantityModal(e) {
            const { productId } = e.currentTarget.dataset;
            const { activityProductWithSkus } = this.data.signinInfo;
            const product = activityProductWithSkus.find(i => i.productId === productId);
            this.setData({
                quantityModal: {
                    show: true,
                    productId,
                    quantity: product.quantity || '',
                },
            });
        },
        handleModify(e) {
            const { productId } = this.data.quantityModal;
            const { activityProductWithSkus } = this.data.signinInfo;
            const product = activityProductWithSkus.find(i => i.productId === productId);
            product.quantity = e.detail;
            this.setData({
                quantityModal: {
                    productId: '',
                    quantity: '',
                },
            });
            this._handleChange();
        },
        handleAdd(e) {
            this.triggerEvent('add');
        },
    }
})
